package com.paddyi.controller;//package com.springcloud.controller;

import com.paddyi.commons.http.HttpResult;
import com.paddyi.commons.utils.DateUtil;
import com.paddyi.commons.utils.MD5;
import com.paddyi.model.User;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.servlet.ShiroHttpSession;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;


/**
 *
 * ClsTradeOrder 控制层
 *
 */
@RestController
public class LoginController extends BaseController {


    @RequestMapping("/ajaxLogin")
    public HttpResult ajaxLogin() {
        return HttpResult.error(401,"请登录!");
    }

    /**
     * 登陆
     *
     * @param userInfo 用户
     */
    @PostMapping(value = "/login")
    public HttpResult login(HttpServletRequest request, @RequestBody User userInfo) {
        // 从SecurityUtils里边创建一个 subject
        Subject subject = SecurityUtils.getSubject();
        // 在认证提交前准备 token（令牌）
        UsernamePasswordToken token = new UsernamePasswordToken(userInfo.getLoginName(), MD5.getMd5Str(userInfo.getPassword()));
        try {
            // 执行认证登陆
            subject.login(token);
            User user = getCurrentUser();
            Map<String,Object> map = new HashMap<>();
            map.put("token", ShiroHttpSession.DEFAULT_SESSION_ID_NAME);
            map.put("user",user.getName());
            map.put("img",user.getImg());
            map.put("createTime",DateUtil.getDateFormat(user.getCreateTime()));
            return HttpResult.ok(map);
        }catch (UnknownAccountException e) {
            return HttpResult.error(402,"账号不存在！");
        } catch (DisabledAccountException e) {
            return HttpResult.error(402,"账号未启用！");
        } catch (IncorrectCredentialsException e) {
            return HttpResult.error(402,"密码错误");
        } catch (ExcessiveAttemptsException e) {
            return HttpResult.error(402,"密码连续输错5次，停用半小时！");
        }
        catch (Throwable e) {
            return HttpResult.error(402,"未知错误，请联系管理员！");
        }
        //根据权限，指定返回数据
//        return "redirect://"+request.getServerName() +":"+ request.getServerPort()  + savedRequest.getRequestUrl();
    }

    @GetMapping("/logout")
    public HttpResult logout(HttpSession session) {
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        return HttpResult.ok("退出登录成功");
    }

}